<template>
    <!-- 有子节点：分类或目录，使用 el-sub-menu -->
    <el-sub-menu v-if="isCategory" :index="item.categoryUrl">
        <template #title>
            <el-icon>
                <Files />
            </el-icon>
            <span class="menu-title" v-if="!isCollapse">{{ item.categoryName }}</span>
        </template>
        <!-- 安全遍历 children，避免 undefined -->
        <MenuNode v-for="child in (item.children || [])" :key="child.categoryUrl || child.id || child.modelname"
            :item="child" :is-collapse="isCollapse" />
    </el-sub-menu>

    <!-- 无子节点：模型叶子，使用 el-menu-item -->
    <!-- <el-menu-item v-else :index="`/dao/${item.modelname}`" :route="{
        path: `/dao/${item.modelname}`,
        query: {
            mid: item.id,
            modelIntro: item.intro,
            servedModelName: item.servedModelName,
            serverUrl: item.serverUrl
        }
    }">
        <template #title>
            <RobotInfo :model="item" />
        </template>
    </el-menu-item> -->
    <el-menu-item v-else :index="`/dao/${item.modelname}`" @click="handleModelClick(item)">
        <template #title>
            <RobotInfo :model="item" />
        </template>
    </el-menu-item>
</template>

<script setup>
import { computed } from 'vue'
import { Files } from '@element-plus/icons-vue'
import RobotInfo from '../robots/RobotInfo.vue'
import { useModelStore } from '@/stores/model'


// 递归组件需要设置自身名称以支持自引用
defineOptions({ name: 'MenuNode' })
const modelStore = useModelStore()

const props = defineProps({
    item: { type: Object, required: true },
    isCollapse: { type: Boolean, default: false }
})

// 新增：点击菜单时将模型信息写入 Pinia
const handleModelClick = (modelItem) => {
    modelStore.setModelInfo({
        id: modelItem.id,
        serverUrl: modelItem.serverUrl,
        modelName: modelItem.modelname, // 注意字段名转换
        intro: modelItem.intro,
        avatar: modelItem.avatar || '',
        servedModelName: modelItem.servedModelName
    })
}

// 根据是否存在 modelname 判断是否为模型叶子；否则视为分类
const isCategory = computed(() => !props.item?.modelname)
</script>